import projectWithenv from '@/models/projectWithenv';
import { syncPostNewBranch } from '../gitlab/index';
import { getSingleBranch } from '../gitlab/apis';
import { privateToken } from '../configs/gitlab';

interface UnionParams {
  id?: string | number;
  project_id: string | number;
  namespace?: string;
  project_name: string;
  branch: string;
  isEdit: boolean;
  mainBranch: string;
  review_status: string;
  env: string;
  developer: string;
  mergeBranchName?: string;
}

// 新增：先查一下是不是存在项目和环境，如果没有，直接加入。如果存在，创建新的合并分支
// 修改：
export const asyncAddUnion = async (params: UnionParams) => {
  const { isEdit, project_name, project_id, env, branch, developer } = params;
  // 编辑
  if (typeof isEdit === 'number') {
    console.log(11);
  }
  // 新增
  const result = await projectWithenv.findOne({ project_id });
  if (result) {
    const { relation_env } = result;
    console.log(relation_env, 'relation_env');
    // 处理小程序
    if (project_id === 12) {
      // 如果环境不存在项目
      if (!relation_env[env]) {
        relation_env[env] = [
          {
            branch,
            isMergeBranch: false,
            developer,
          },
        ];
      }
      // if (Array.isArray(relation_env[env].children)) {
      //   relation_env[env].children.push({
      //     branch,
      //     isMergeBranch: false,
      //     developer,
      //   });
      // } else {
      //   relation_env[env].children = [
      //     {
      //       branch,
      //       isMergeBranch: false,
      //       developer,
      //     },
      //   ];
      // }
      const result2 = await projectWithenv.update(result, { project_name: params.project_name });
      return result2;
    }
    // 如果只有一个分支不是合并分支，那么创建合并分支，如果已经存在合并分支，那么往合并分支children里push当前分支
    // 1、当前环境没有被使用
    if (!relation_env[env]) {
      result.relation_env[env] = {
        branch,
        isMergeBranch: false,
        developer,
      };
      const result2 = await projectWithenv.update(result, { project_name: params.project_name });
      return result2;
    }
    // 2、当前环境有合并分支
    if (relation_env[env].isMergeBranch) {
      relation_env[env].children.push({
        branch,
        isMergeBranch: false,
        developer,
      });
      await projectWithenv.update(result, { project_name: params.project_name });
      return {
        code: '1001',
        message: '当前环境已经存在合并分支，请手动合并代码',
      };
    }
    // 3、当前环境只有一个需求在使用
    if (relation_env[env].branch && !relation_env[env].isMergeBranch) {
      return {
        code: '1002',
        message: '当前环境被占用，请创建合并分支',
      };
    }
    return [];
  }
  console.log('当前项目没有占用');
  let temp = {};
  // 处理微信小程序分支
  if (project_id === 12) {
    temp = {
      project_name,
      project_id,
      relation_env: {
        [env]: {
          branch: 'robot',
          isMergeBranch: true,
          children: [
            {
              branch,
              isMergeBranch: false,
              developer,
            },
          ],
        },
      },
    };
  } else {
    temp = {
      project_name,
      project_id,
      relation_env: {
        [env]: {
          branch,
          isMergeBranch: false,
          developer,
        },
      },
    };
  }
  const res = await projectWithenv.insert(temp);
  return res;
};

// 创建新的合并分支
export const asyncAddMergeBranch = async (params: UnionParams) => {
  const { isEdit, project_name, project_id, env, branch, developer, mergeBranchName } = params;
  // 编辑
  if (typeof isEdit === 'number') {
    console.log(11);
  }
  // 新增
  const result = await projectWithenv.findOne({ project_id });
  if (result) {
    const { relation_env } = result;
    // 当前环境只有一个需求在使用
    if (relation_env[env].branch && !relation_env[env].isMergeBranch) {
      const defineBranch = mergeBranchName as string;
      const mergeBranch = {
        branch: defineBranch,
        isMergeBranch: true,
        children: [
          {
            ...relation_env[env],
            isMergeBranch: false,
          },
          {
            branch,
            isMergeBranch: false,
            developer,
          },
        ],
      };
      // 判断gitlab上有没有这个分支
      const branchRes: any = await getSingleBranch({ private_token: privateToken, id: project_id, branch: defineBranch }).catch((err) => null);
      console.log(branchRes, 'branchRes');
      // 如果存在
      if (!branchRes || !branchRes.name) {
        // 往gitlab上发个创建合并分支的请求
        await syncPostNewBranch({ id: project_id, ref: relation_env[env].branch, branch: defineBranch });
      }
      relation_env[env] = mergeBranch;
      const result2 = await projectWithenv.update(result, { project_name });
      return result2;
    }
    return [];
  }
  return [];
};
// 获取环境使用记录
export const asyncGetUnion = async (params: any) => {
  const result = await projectWithenv.getList({});
  return result;
};
// 删除环境使用记录
export const asyncDeleteUnion = async (params: UnionParams) => {
  const { env, branch, project_name } = params;
  const result = await projectWithenv.findOne({ project_name });
  if (result) {
    const { relation_env } = result;
    // 是合并分支
    if (relation_env[env] && relation_env[env].isMergeBranch) {
      console.log(111);
      if (relation_env[env].children) {
        for (let i = 0; i < relation_env[env].children.length; i += 1) {
          if (relation_env[env].children[i].branch === branch) {
            relation_env[env].children.splice(i, 1);
            break;
          }
        }
        if (relation_env[env].children.length === 1) {
          // 如果合并分支只剩一个，那么不要合并分支
          relation_env[env] = {
            branch: relation_env[env].children[0].branch,
            isMergeBranch: false,
            developer: relation_env[env].children[0].developer,
          };
        }
      }
      const result2 = await projectWithenv.update(result, { project_name });
      return result2;
    }
    // 不是合并分支
    // 兼容一下前端误操作，没有创建合并分支，直接把弹框取消的情况
    if (relation_env[env] && relation_env[env].branch === branch) {
      delete relation_env[env];
      const result2 = await projectWithenv.update(result, { project_name });
      return result2;
    }
    return [];
  }
  return [];
};
